package com.lincoln.cartoon.controller;

import com.lincoln.cartoon.updater.UpdaterService;
import com.lincoln.cartoon.updater.enums.UpdateTypeEnum;
import com.lincoln.cartoon.updater.interfaces.BaseUpdater;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.*;

@Controller
public class ApiController {
    Map<String, Map<String, Object>> res = null;

    @Autowired
    UpdaterService updaterService;

    private Map<String, Map<String, Object>> getRes() {
        if (res == null) {
            res = new LinkedHashMap<>();
            String path = "";
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                path = "D:/mh/";
            } else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
                path = "/mh/";
            }
            File file = new File(path);
            List<File> subDirs = Arrays.asList(file.listFiles());
            subDirs.sort(Comparator.comparing(File::lastModified));
            for (File subDir : subDirs) {
                if (subDir.isDirectory()) {
                    Map<String, Object> subInfo = new HashMap<>();
                    List<File> subs = Arrays.asList(subDir.listFiles());
                    for (File sub : subs) {
                        if (sub.isDirectory()) {
                            Map<String, Object> info = new HashMap<>();
                            info.put("size", sub.listFiles().length);
                            subInfo.put(sub.getName(), info);
                        }
                    }
                    res.put(subDir.getName(), subInfo);
                }
            }
        }
        return res;
    }

    @ResponseBody
    @GetMapping("/api/catalog-list")
    public Map<String, Map<String, Object>> catalogList(Boolean refresh) {
        if (refresh != null && refresh) {
            res = null;
        }
        return getRes();
    }

    @ResponseBody
    @GetMapping("/api/update")
    public Map<String, Object> update(Integer updateType, String name) {
        Map<String, Object> res = new HashMap<>();
        BaseUpdater updater = UpdaterService.getUpdater(UpdateTypeEnum.findByValue(updateType), name);
        if (updater.isUpdate()) {
            res.put("result", false);
            res.put("msg", "该项目正在更新,当前进度" + updater.percent() + "%");
            return res;
        } else {
            try {
                updater.invoke(new HashMap<>());
                res.put("result", true);
                return res;
            } catch (Exception e) {
                e.printStackTrace();
                res.put("result", false);
                res.put("msg", "异常:" + e.getMessage());
                return res;
            }
        }
    }
}
